from django.shortcuts import render
from django.http import HttpResponse
from .models import UpdateDataSet
from .models import User
from .models import MbControl
from .models import MushBox
from .uclass import CJsonEncoder
from django.forms.models import model_to_dict
from datetime import datetime, timezone, timedelta
import json

import json
import datetime


def init(request):
    user = User()
    user.user_id = 1
    user.user_name = 'admin'
    user.gmt_time = datetime.datetime.now()
    user.save()
    # 初始化蘑菇箱
    mushbox = MushBox()
    mushbox.mb_id = 1
    mushbox.userid = 1
    mushbox.mb_des = "第一只可爱的蘑菇箱"
    mushbox.mb_name = "蘑菇箱"
    mushbox.gmt_time = datetime.datetime.now()
    # 控制初始化
    control = MbControl()
    control.mb_hummin = 30
    control.mb_hummax = 45
    control.mb_temmin = 10
    control.mb_hummax = 20
    control.mb_enhotfan = 1
    control.mb_enfan = 1
    control.mb_encoldfan = 0
    # 是否开启加湿器
    control.mb_enwoter = 0
    return HttpResponse("success")


# 上传数据
def update_date(request):
    data = UpdateDataSet()
    data.mbid_id = request.GET.get("mbid")
    data.mb_enfan = request.GET.get("enfan")
    data.mb_hum = request.GET.get("hum")
    data.mb_enhotfan = request.GET.get("enhotfan")
    data.mb_isgrow = request.GET.get("isgrow")
    data.mb_temp = request.GET.get("temp")
    data.mb_enhum = request.GET.get("enhum")
    data.mb_isqipe = request.GET.get("isqipe")
    data.mb_encoldfan = request.GET.get("encoldfan")
    # 时区设置
    tz_utc_8 = timezone(timedelta(hours=-8))
    data.mb_time = datetime.datetime.now().replace(tzinfo=tz_utc_8)
    data.save()

    control_data = MbControl.objects.get(mbid=data.mbid_id)
    controls = '#%s%s%s%s%s' % (
        control_data.mb_model, control_data.mb_enfan, control_data.mb_enhotfan, control_data.mb_encoldfan,
        control_data.mb_enhum
    )
    hummax = "{0:.4}".format(repr(control_data.mb_hummax).zfill(3)).replace(".", "")
    hummin = "{0:.4}".format(repr(control_data.mb_hummin).zfill(3)).replace(".", "")
    temmax = "{0:.4}".format(repr(control_data.mb_temmax).zfill(3)).replace(".", "")
    temmin = "{0:.4}".format(repr(control_data.mb_temmin).zfill(3)).replace(".", "")
    enhumtime = "{0:.3}".format(repr(control_data.mb_waterruntime).zfill(3)).replace(".", "")
    humspantime = "{0:.2}".format(repr(control_data.mb_waterspan).zfill(2)).replace(".", "")
    result = controls + hummax + hummin + temmax + temmin + enhumtime + humspantime + "#"
    return HttpResponse(result)


def get_control(request):
    control_data = MbControl.objects.get(mbid=1)
    data_dic = model_to_dict(control_data)
    return HttpResponse(json.dumps(data_dic))


# 获取数据
def get_data(request):
    mbid = request.GET.get("mbid")
    if mbid == None:
        return HttpResponse("请告诉我蘑菇箱的id")
    tz_utc_8 = timezone(timedelta(hours=-8))
    now_date = datetime.datetime.now().replace(tzinfo=tz_utc_8).replace(minute=0) + datetime.timedelta(
        hours=1)  # - datetime.timedelta(hours=24, minutes=0, seconds=0)
    listData = []
    print(now_date)
    for i in range(1, 25):
        start_date = now_date - datetime.timedelta(hours=1, minutes=0, seconds=0)
        print(start_date)
        data = UpdateDataSet.objects.filter(mbid=1, mb_time__range=(start_date, now_date)).first()
        if i is 1 and data is None:
            return HttpResponse("error")
        if data is not None:
            listData.append(model_to_dict(data))
        else:
            listData.append(listData[i - 2])
        now_date = start_date
    status = 0
    describe = "数据获取成功"
    result = {"status": status, "describe": describe, "data": listData}
    return HttpResponse(json.dumps(result, ensure_ascii=False, cls=CJsonEncoder))


def get_current(request):
    mbid = request.GET.get("mbid")
    if mbid is None:
        return HttpResponse("请告诉我蘑菇箱的id")
    data = UpdateDataSet.objects.filter(mbid=mbid)
    data_dic = model_to_dict(data.last())
    status = 0
    describe = "数据获取成功"
    result = {"status": status, "describe": describe, "data": data_dic}
    return HttpResponse(json.dumps(result, ensure_ascii=False, cls=CJsonEncoder))


def client_login(request):
    username = request.GET.get("username")
    password = request.GET.get("password")
    user = User.objects.get(user_name=username)
    if user == None:
        return HttpResponse("error")
    if user.user_password == password:
        result = {"status": 200, "describe": "登录成功", "data": user.user_id}
        return HttpResponse(json.dumps(result, cls=CJsonEncoder, ensure_ascii=False))
    return HttpResponse("error")


def client_control(request):
    mbid = request.GET.get("mbid")
    # 控制模式
    mb_model = request.GET.get("model")
    # 温度上限
    mb_temmax = request.GET.get("temmax")
    # 温度下限
    mb_temmin = request.GET.get("temmin")
    # 湿度上限
    mb_hummax = request.GET.get("hummax")
    # 湿度下限
    mb_hummin = request.GET.get("hummin")
    # 是否开启风扇
    mb_enfan = request.GET.get("enfan")
    # 是否开启热风扇
    mb_enhotfan = request.GET.get("enhotfan")
    # 是否开启冷风扇
    mb_encoldfan = request.GET.get("encoldfan")
    # 是否开启加湿器
    mb_enhum = request.GET.get("enhum")

    # 加湿器运行时间
    mb_waterruntime = request.GET.get("waterruntime")
    # 加湿器间隔时间
    mb_waterspantime = request.GET.get("waterspantime")

    if mbid is None:
        return HttpResponse("mbid is not a null")
    control = MbControl.objects.filter(mbid=mbid).last()

    if mb_model is not None:
        control.mb_model = mb_model

    if mb_temmax is not None:
        control.mb_temmax = mb_temmax

    if mb_temmin is not None:
        control.mb_temmin = mb_temmin

    if mb_hummax is not None:
        control.mb_hummax = mb_hummax

    if mb_hummin is not None:
        control.mb_hummin = mb_hummin

    if mb_enfan is not None:
        control.mb_enfan = mb_enfan

    if mb_enhotfan is not None:
        control.mb_enhotfan = mb_enhotfan

    if mb_encoldfan is not None:
        control.mb_encoldfan = mb_encoldfan

    if mb_enhum is not None:
        control.mb_enhum = mb_enhum

    if mb_waterruntime is not None:
        control.mb_waterruntime = mb_waterruntime

    if mb_waterspantime is not None:
        control.mb_waterspantime = mb_waterspantime

    control.save()
    return HttpResponse("success")
